<template>
  <div class="merchant-management">
    <el-card>
      <div slot="header" class="clearfix">
        <span class="page-title">区域商家管理</span>
        <div class="header-actions">
          <el-button
            class="refresh-btn"
            type="primary"
            icon="el-icon-refresh"
            @click="refreshData">
            <span class="btn-text">刷新数据</span>
          </el-button>
        </div>
      </div>

      <div class="search-form">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="商家名称">
            <el-input v-model="searchForm.name" placeholder="请输入商家名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              placeholder="选择开始时间"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              placeholder="选择结束时间"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <configurable-table
        :columns="tableColumns"
        :data="tableData"
        :loading="loading"
        :show-pagination="true"
        :current-page.sync="pagination.current"
        :page-size.sync="pagination.size"
        :pagination-total="pagination.total"
        :default-sort="{prop: 'createTime', order: 'descending'}"
        @page-change="loadData"
        border>
        <!-- 商家名称列 -->
        <template #name="{ row }">
          <div class="merchant-info">
            <i class="el-icon-shop"></i>
            <span>{{ row.name }}</span>
          </div>
        </template>
        <!-- 联系电话列 -->
        <template #phone="{ row }">
          <div class="phone-info">
            <i class="el-icon-phone"></i>
            <span>{{ row.phone }}</span>
          </div>
        </template>
        <!-- 地址列 -->
        <template #address="{ row }">
          <div class="address-info">
            <i class="el-icon-location"></i>
            <span>{{ row.address }}</span>
          </div>
        </template>
        <!-- 业务员列 -->
        <template #salesmanName="{ row }">
          <div class="salesman-info">
            <i class="el-icon-user"></i>
            <span>{{ row.salesmanName || '编号'+row.salesmanNo+'业务员' }}</span>
          </div>
        </template>
        <!-- 锁定用户数列 -->
        <template #lockNum="{ row }">
          <div class="user-count-display">
            <span class="count-value">{{ row.lockNum || 0 }}</span>
            <el-tag
              :type="getUserCountTag(row.lockNum || 0)"
              size="mini"
              class="count-tag">
              {{ getUserCountLevel(row.lockNum || 0) }}
            </el-tag>
          </div>
        </template>
        <!-- 状态列 -->
        <template #status="{ row }">
          <el-tag :type="getStatusTag(row.status)">
            {{ row.statusText }}
          </el-tag>
        </template>
        <!-- 入驻时间列 -->
        <template #createTime="{ row }">
          <div class="time-info">
            <i class="el-icon-time"></i>
            <span>{{ row.createTime }}</span>
          </div>
        </template>
        <!-- 操作列 -->
        <template #actions="{ row }">
          <el-button size="mini" icon="el-icon-view" @click="handleView(row)">查看</el-button>
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEditUserCount(row)">修改用户数</el-button>
          <el-button size="mini" type="success" icon="el-icon-chat-line-square" @click="handleContact(row)">联系</el-button>
        </template>
      </configurable-table>
    </el-card>

    <!-- 修改用户数量对话框 -->
    <el-dialog
      title="修改锁定用户数量"
      :visible.sync="userCountDialogVisible"
      width="520px"
      custom-class="action-dialog"
      :close-on-click-modal="false">

      <!-- 商家信息卡片 -->
      <div class="info-card">
        <div class="card-header">
          <i class="el-icon-shop"></i>
          <span>商家信息</span>
        </div>
        <div class="info-content">
          <div class="info-item">
            <span class="info-label">
              <i class="el-icon-shop"></i>
              商家名称：
            </span>
            <span class="info-value">{{ userCountForm.merchantName }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">
              <i class="el-icon-user-solid"></i>
              当前用户数：
            </span>
            <span class="info-value user-count-display-value">{{ userCountForm.currentCount || 0 }}</span>
            <el-tag
              :type="getUserCountTag(userCountForm.currentCount || 0)"
              size="small"
              class="count-status-tag">
              {{ getUserCountLevel(userCountForm.currentCount || 0) }}
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 修改配置区域 -->
      <div class="form-section">
        <div class="section-title">
          <i class="el-icon-edit"></i>
          <span>修改用户数量</span>
        </div>

        <el-form
          :model="userCountForm"
          :rules="userCountRules"
          ref="userCountForm"
          label-width="140px"
          class="action-form">

          <el-form-item label="新的锁定用户数" prop="newCount">
            <div class="input-wrapper">
              <el-input-number
                v-model="userCountForm.newCount"
                :min="0"
                :max="userCountForm.lockNumLimit || 0"
                :precision="0"
                controls-position="right"
                placeholder="请输入新的用户数量"
                style="width: 100%">
              </el-input-number>
            </div>
            <div class="form-tip">
              <i class="el-icon-info"></i>
              <span>输入新的锁定用户数量，范围为 0-{{ userCountForm.lockNumLimit || 0 }}</span>
            </div>
          </el-form-item>

          <!-- 数量变化提示 -->
          <el-form-item v-if="userCountForm.newCount !== null && userCountForm.currentCount !== null">
            <div class="count-change-info">
              <div class="change-label">
                <i class="el-icon-sort"></i>
                变化量：
              </div>
              <div
                class="change-value"
                :class="{
                  'change-positive': userCountForm.newCount > userCountForm.currentCount,
                  'change-negative': userCountForm.newCount < userCountForm.currentCount,
                  'change-zero': userCountForm.newCount === userCountForm.currentCount
                }">
                <span v-if="userCountForm.newCount > userCountForm.currentCount">
                  <i class="el-icon-arrow-up"></i>
                  +{{ userCountForm.newCount - userCountForm.currentCount }}
                </span>
                <span v-else-if="userCountForm.newCount < userCountForm.currentCount">
                  <i class="el-icon-arrow-down"></i>
                  {{ userCountForm.newCount - userCountForm.currentCount }}
                </span>
                <span v-else>
                  <i class="el-icon-check"></i>
                  无变化
                </span>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="userCountDialogVisible = false">
          <i class="el-icon-close"></i>
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleSaveUserCount"
          :loading="userCountLoading">
          <i class="el-icon-check"></i>
          {{ userCountLoading ? '保存中...' : '确定保存' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAgentMerchantPage, updateLockNum } from '@/api/aggregation'

export default {
  name: 'AgentMerchantManagement',
  data() {
    return {
      loading: false,
      searchForm: {
        name: '',
        startTime: '',
        endTime: ''
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 表格列配置
      tableColumns: [
        { prop: 'id', label: '商家ID', minWidth: 80, align: 'center' },
        { prop: 'name', label: '商家名称', minWidth: 150, showOverflowTooltip: true, slot: 'name' },
        { prop: 'phone', label: '联系电话', minWidth: 130, slot: 'phone' },
        { prop: 'address', label: '地址', minWidth: 200, showOverflowTooltip: true, slot: 'address' },
        { prop: 'salesmanName', label: '业务员', minWidth: 150, slot: 'salesmanName' },
        { prop: 'lockNum', label: '锁定用户数', minWidth: 120, sortable: true, slot: 'lockNum' },
        { prop: 'status', label: '商家状态', minWidth: 100, slot: 'status' },
        { prop: 'createTime', label: '入驻时间', minWidth: 180, sortable: true, slot: 'createTime' },
        { prop: 'actions', label: '操作', minWidth: 200, slot: 'actions', fixed: false }
      ],
      userCountDialogVisible: false,
      userCountLoading: false,
      userCountForm: {
        id: null,
        merchantName: '',
        currentCount: 0,
        newCount: null,
        lockNumLimit: 0
      },
      userCountRules: {
        newCount: [
          { required: true, message: '请输入新的用户数量', trigger: 'blur' },
          { type: 'number', min: 0, message: '用户数量不能小于0', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== null && value !== undefined) {
                const maxLimit = this.userCountForm.lockNumLimit || 0
                if (value > maxLimit) {
                  callback(new Error(`用户数量不能超过限制值 ${maxLimit}`))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.current,
          size: this.pagination.size,
          ...this.searchForm
        }

        const response = await getAgentMerchantPage(params)

        if (response.code === 0) {
          this.tableData = response.data.list || []
          this.pagination.total = response.data.total || 0
        } else {
          this.tableData = []
          this.pagination.total = 0
        }
      } catch (error) {
        Logger.error('加载商家数据失败:', error)
        this.tableData = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.pagination.current = 1
      this.loadData()
    },

    handleReset() {
      this.searchForm = {
        name: '',
        startTime: '',
        endTime: ''
      }
      this.loadData()
    },

    handleView(row) {
      // 跳转到商家详情页面
      this.$router.push({
        path: '/agent/merchant-detail',
        query: { id: row.id }
      })
    },

    handleEditUserCount(row) {
      this.userCountForm = {
        id: row.id,
        merchantName: row.name,
        currentCount: row.lockNum || 0,
        newCount: row.lockNum || 0,
        lockNumLimit: row.lockNumLimit || 0
      }
      this.userCountDialogVisible = true
      // 重置表单验证状态
      this.$nextTick(() => {
        if (this.$refs.userCountForm) {
          this.$refs.userCountForm.clearValidate()
        }
      })
    },

    async handleSaveUserCount() {
      this.$refs.userCountForm.validate(async (valid) => {
        if (valid) {
          this.userCountLoading = true
          try {
            const response = await updateLockNum({
              id: this.userCountForm.id,
              lockNum: this.userCountForm.newCount
            })

            if (response.code === 0) {
              this.$message.success('修改用户数量成功')
              this.userCountDialogVisible = false
              // 刷新数据
              this.loadData()
            } else {
              this.$message.error(response.msg || '修改失败')
            }
          } catch (error) {
            console.error('修改用户数量失败:', error)
            this.$message.error('修改失败')
          } finally {
            this.userCountLoading = false
          }
        }
      })
    },


    // 刷新数据
    refreshData() {
      this.$message.success('数据已刷新')
      this.loadData()
    },

    // 联系商家
    handleContact(row) {
      this.$message.info(`正在联系商家：${row.name}，电话：${row.phone}`)
    },


    // 获取用户数量标签类型
    getUserCountTag(count) {
      if (count >= 30) return 'success'
      if (count >= 20) return 'warning'
      return 'info'
    },

    // 获取用户数量等级
    getUserCountLevel(count) {
      if (count >= 30) return '活跃'
      if (count >= 20) return '一般'
      return '较少'
    },

    // 获取状态标签类型
    getStatusTag(status) {
      const statusMap = {
        0: 'success',  // 正常
        1: 'danger'    // 停用
      }
      return statusMap[status] || 'info'
    },
  }
}
</script>

<style scoped>
.merchant-management {
  padding: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.header-actions {
  float: right;
}

.refresh-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.merchant-info, .phone-info, .address-info, .salesman-info, .time-info {
  display: flex;
  align-items: center;
}

.merchant-info i, .phone-info i, .address-info i, .salesman-info i, .time-info i {
  margin-right: 5px;
  color: #409eff;
}

.user-count-display {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}

.count-value {
  font-weight: bold;
  color: #303133;
}

.count-tag {
  margin-left: 5px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 用户数量对话框样式优化 */
::v-deep .action-dialog {
  .user-count-display-value {
    font-size: 16px;
    font-weight: 600;
    color: #409eff;
    margin-right: 8px;
  }

  .count-status-tag {
    margin-left: 0;
  }

  .form-tip {
    display: flex;
    align-items: center;
    margin-top: 8px;
    font-size: 13px;
    color: #909399;
    line-height: 1.5;

    i {
      margin-right: 6px;
      color: #409eff;
    }
  }

  .count-change-info {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background: #f7f8fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;
    margin-top: 8px;

    .change-label {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #6c757d;
      font-weight: 500;
      margin-right: 12px;

      i {
        margin-right: 6px;
        color: #909399;
      }
    }

    .change-value {
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
      padding: 4px 12px;
      border-radius: 6px;
      transition: all 0.3s ease;

      i {
        margin-right: 4px;
      }

      &.change-positive {
        color: #67c23a;
        background: #f0f9ff;
        border: 1px solid #e1f5f0;
      }

      &.change-negative {
        color: #f56c6c;
        background: #fff1f0;
        border: 1px solid #ffe8e6;
      }

      &.change-zero {
        color: #909399;
        background: #f5f7fa;
        border: 1px solid #e4e7ed;
      }
    }
  }
}
</style>
